// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    const user = wxContext.OPENID;
    const projectId = event.projectId;
    if (!projectId) return { err: '缺少projectId' }
    //判断角色是否为master
    console.log('projectId',projectId,'\nuserId',user);
    let res =await db.collection('code').where({
        group: projectId,
        userId: user
    }).get()
    if (res.data && res.data.length) {
        if (res.data[0].role !== 'master') return { err: '权限错误' }
        await Promise.all([
            //删除项目中所有任务
            new Promise(resolve => {
                //获得项目中所有任务
                db.collection('mission').where({ projectId }).field({ _id: true }).get()
                    .then(res => {
                        if (res.data && res.data.length) {
                            //删除任务对应记录
                            Promise.all(res.data.map(item => new Promise(resolve => {
                                db.collection('missionLog').where({ missionId: item._id }).remove().then(resolve)
                            }))).then(resolve)
                        } else {
                            resolve()
                        }
                    })
                db.collection('mission').where({
                    projectId
                }).remove()
            })
            ,
            //删除项目中所有成员
            db.collection('code').where({
                group: projectId
            }).remove,
            //删除项目
            db.collection('group').doc(projectId).remove()
        ])
    }else{
        return {err:'项目中没有对应用户'}
    }
}